<template>
  <div class="pad_10">
    <el-form ref="queryRef" :inline="true" label-width="68px">
      <el-form-item>
        <el-button @click="handleQuery">保存</el-button>
        <el-button @click="Cancel">取消</el-button>
        <!-- <el-button :disabled="!route.query.id" @click="auditFun">审核</el-button> -->
      </el-form-item>
    </el-form>
    <el-divider />
    <SetUserSelect
      :key="keys"
      ref="setUserSelect"
      class="queryForm"
      :labelwidth="100"
      :isShowUserBtn="false"
      :buttonIsShow="false"
      :formData="bill"
      :queryParams="datas"
      @selChangeFun="changeFun"
    ></SetUserSelect>
    <el-form ref="queryFormmin" :model="datas" label-width="75px">
      <el-card class="box-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>上传资料</span>
          </div>
        </template>

        <el-row :gutter="20" align="stretch">
          <el-col :span="12">
            <div  :style="{'width': '100%','display': 'flex','pointer-events': (percentage == 100 || percentage == 0)? 'auto': 'none'}">
              <el-form-item
                label-width="85px"
                label="资料:"
                prop="url"
                :rules="[
                  {
                    required: true,
                    message: '请上传资料',
                    trigger: ['blur'],
                  },
                ]"
              >
                <file-upload
                  @setFile="setFileFun"
                  :autoUpload="false"
                  :isShowTip="false"
                  showTipText=""
                  :limit="1"
                  v-model="datas.url"
                ></file-upload>
              </el-form-item>
              <div style="width: 100%; margin-left: 20px">
                <el-progress
                  :text-inside="true"
                  :stroke-width="26"
                  :percentage="percentage"
                />
                <!-- <el-progress :text-inside="true" :stroke-width="1" :percentage="70" /> -->
              </div>
            </div>
          </el-col>
        </el-row>
        <div></div>
      </el-card>
    </el-form>
  </div>
</template>
<script setup>

import axios from "axios";
import { getToken } from "@/utils/auth";
import { ref, getCurrentInstance, watch } from "vue";
import { addresource, resourceId, eitHresource } from "@/api/dataManag";
import { ElLoading, ElMessage } from 'element-plus'
import FileMd5 from "./models/file-md5.js";
import data from "./data";
import { useRoute } from "vue-router";
const { bill, datas } = data;
const { proxy } = getCurrentInstance();
let proxys = proxy;
const route = useRoute();
let keys = ref("");
const { data_manag_type, data_manag_status } = proxys.useDict(
  "data_manag_type",
  "data_manag_status"
);
watch(data_manag_type, (newV, oldV) => {
  bill.value[3].selectData = data_manag_type;
  keys.value = new Date().getTime();
});
watch(data_manag_status, (newV, oldV) => {
  bill.value[4].selectData = data_manag_status;
  keys.value = new Date().getTime();
});
route.query.id &&
  resourceId(route.query.id).then((res) => {
    res.data.status = "" + res.data.status;
    res.data.type = "" + res.data.type;
    res.data.setTime = res.data.createTime;
    datas.value = res.data;
  });
const handleQuery = function () {
  Promise.all([
    proxys.$refs.setUserSelect.submitForm(),
    proxys.$refs.queryFormmin.validate(),
  ]).then((valid) => {
    (!route.query.id ? addresource : eitHresource)(valid[0]).then(() => {
      proxys.$modal.msgSuccess(`${route.query.id ? "修改" : "新增"}成功`);
      Cancel();
    });
  });
};
const changeFun = function (e) {
  console.log(e);
};
const Cancel = () => {
  datas.value = {};
  const obj = { path: "/material/dataManagList" };
  proxys.$tab.closeOpenPage(obj);
};
const percentage = ref(0);
const setFileFun = (file) => {
  const loading = ElLoading.service({
    lock: true,
    text: '文件检验中，请稍等...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  // const uploadFileUrl = ''; // 上传的图片服务器地址
  // var file = document.getElementById("filesa").files[0]
  // console.log("1242351235", file);
  let identifier = null; // 文件标识
  // let chunkSize = 2097152;                             // Read in chunks of 2MB
  let chunkSize = 1097152; // 分块大小
  let chunks = Math.ceil(file.size / chunkSize);
  // console.log("fasdg341235", chunks);
  
  // return
  //  前端检验生成文件唯一的md5
  FileMd5(file.raw, (e, md5) => {
    console.log('fasdg321412', md5)
    // f["md5"] = md5;
    // f.status = 1;
    loading.close()
    // // 调用后台接口获取路径  如果没有路径就说明没有上传过  要重新上传  或者上传一半断点续传
    axios({
      method: "get",
      url: import.meta.env.VITE_APP_BASE_API + "/file/background/file/upload?identifier=" + md5,
      // params: from1,
      headers: {
        // 'Content-Type': 'application/x-www-form-urlencoded',
        token: getToken(),
      },
    }).then((resmin) => {
      console.log('fasdg4325132614', resmin)
      identifier = md5;
      console.log("fasdg21432351", identifier);

      var boolname = file.name;

      let is = 0;
      if (resmin.data.data.skipUpload) {
        
        // 是否需要合并
        if (resmin.data.data.needMerge) {
          var from3 = new FormData();
          from3.append("identifier", md5);
          from3.append("filename", boolname);
          // // 合并文件
          axios({
            method: "post",
            url: import.meta.env.VITE_APP_BASE_API + "/file/background/file/merge",
            data: from3,
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
              token: getToken(),
            },
          }).then((vals) => {
            // 获取路径
            axios({
              method: "get",
              url: import.meta.env.VITE_APP_BASE_API + "/file/background/file/upload?identifier=" + md5,
              // params: from1,
              headers: {
                // 'Content-Type': 'application/x-www-form-urlencoded',
                token: getToken(),
              },
            }).then((resmax) => {
              ElMessage({
                message: '上传成功',
                type: 'success',
              })
              // console.log('fasdg213124123512', res)
              percentage.value = 100;
              datas.value.url = resmax.data.data.url;
            });
          });
        } else {
          ElMessage({
            message: '上传成功',
            type: 'success',
          })
          datas.value.url = resmin.data.data.url;
          percentage.value = 100;
        }
        return;
      } else {
        is = resmin.data.data.uploaded[0] || 0;
      }
      const funa = async () => {
        var from = new FormData();
        // let chunkNumber:any = 0 //当前文件块

        let currentChunkSize = chunkSize; // 当前分块大小
        let totalSize = file.size; // 总大小
        let relativePath = "./bul"; // 相对路径
        let totalChunks = chunks; // 总块数

        from.append("chunkSize", chunkSize);
        from.append("currentChunkSize", currentChunkSize);
        from.append("totalSize", totalSize);
        from.append("identifier", identifier);
        from.append("filename", boolname);
        from.append("relativePath", relativePath);
        from.append("totalChunks", totalChunks);
        from.append("chunkNumber", is);
        var bool = null;
        // console.log('fsadg123124', file.raw.size) // 63108279
        // console.log('334455', file.raw.slice(2097152, 2097152))
        // return
        // console.log('889900', chunkSize)
        if (is == totalChunks - 1) {
          bool = file.raw.slice(is * chunkSize, totalSize);
          
        } else {
          bool = file.raw.slice(is * chunkSize, is * chunkSize + chunkSize);
          percentage.value = (((is * chunkSize) / totalSize) * 100).toFixed(2);
        }

        var boolfile = new File([bool], boolname);
        from.append("file", boolfile);
        let datasmin = await axios({
          method: "post",
          url: import.meta.env.VITE_APP_BASE_API + "/file/background/file/upload",
          data: from,
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            token: getToken(),
          },
        });
        is++;
        console.log("fasdf411223344", datasmin);
        if (is >= totalChunks) {
          var from1 = new FormData();
          from1.append("identifier", identifier);

          //
          var from2 = new FormData();
          from2.append("identifier", identifier);
          from2.append("filename", boolname);
         // 合并文件
          axios({
            method: "post",
            url: import.meta.env.VITE_APP_BASE_API + "/file/background/file/merge",
            data: from2,
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
              token: getToken(),
            },
          }).then((vals) => {
            //  获取文件路径
            axios({
              method: "get",
              url: import.meta.env.VITE_APP_BASE_API + "/file/background/file/upload?identifier=" + identifier,
              // params: from1,
              headers: {
                // 'Content-Type': 'application/x-www-form-urlencoded',
                token: getToken(),
              },
            }).then((res) => {
              ElMessage({
                message: '上传成功',
                type: 'success',
              })
              // console.log('fasdg213124123512', res)
              datas.value.url = res.data.data.url;
              percentage.value = 100;
            });
          });
        } else {
          funa();
        }
      };
      funa();
    });
  });

  // return
};
</script>
<style scoped>
.pad_10 {
  padding: 10px;
}
.pad_10 .el-form--inline .el-form-item {
  margin: 0;
}
.el-divider--horizontal {
  margin: 10px 0;
}
</style>